package com.adee.design.structure.proxy.dynamicproxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
// 动态代理实质：增强方法功能。代理的是方法，在方法执行前后加上一些逻辑，使得该方法功能增强
// cglib动态代理可以为没有实现接口的类创建代理
public class Test {
    public static void main(String[] args) {
        LawyerInterceptor lawyerInterceptor = new LawyerInterceptor(new Zhangsan());
        Zhangsan zs = (Zhangsan) Enhancer.create(Zhangsan.class, lawyerInterceptor);
        zs.speak();
        System.out.println("zs:" + zs);
        System.out.println(zs.getClass());
    }
}

// 定义一个方法拦截器，即代理逻辑。基本类似于jdk的InvocationHandler
class LawyerInterceptor implements MethodInterceptor {
    private Object obj;
    public LawyerInterceptor(Object obj) {
        this.obj = obj;
    }
    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        if("speak".equals(method.getName())) {
            System.out.println("引用法律条文");
            try {
                Object invoke = method.invoke(obj, args);
                System.out.println("得出结论：打人是不对的");
                return invoke;
            } catch (Exception e) {
                System.out.printf("执行原方法[{}]抛出异常\n", method.getName());
                e.printStackTrace();
            }
        }
        return null;
    }
}

class Zhangsan {
    public void speak() {
        System.out.println("Zhangsan被老婆打了");
    }
}
